import tkinter as tk
from tkinter import filedialog
import os
import pandas as pd

def select_and_read_files(file_type='csv'):
    """
    Open a file dialog to select multiple files and read them into DataFrames.
    
    Parameters:
    file_type: 'csv', 'excel', or 'json'
    
    Returns:
    dfs: list of DataFrames
    filenames: list of filenames
    """

    if not os.path.exists('result'):
        os.makedirs('result')

    # Create a root window and hide it
    root = tk.Tk()
    root.withdraw()
    
    # Set file types for dialog
    if file_type == 'csv':
        filetypes = [("CSV files", "*.csv"), ("All files", "*.*")]
    elif file_type == 'excel':
        filetypes = [("Excel files", "*.xlsx *.xls"), ("All files", "*.*")]
    elif file_type == 'json':
        filetypes = [("JSON files", "*.json"), ("All files", "*.*")]
    else:
        filetypes = [("All files", "*.*")]
    
    # Open file dialog to select multiple files
    print("Please select files to analyze...")
    file_paths = filedialog.askopenfilenames(
        title="Select beam data files",
        filetypes=filetypes
    )
    
    if not file_paths:
        print("No files selected. Exiting.")
        return [], []
    
    dfs = []
    filenames = []
    
    print(f"Selected {len(file_paths)} files. Processing...")
    
    for filepath in file_paths:
        filename = os.path.basename(filepath)
        print("=" * 50)
        print(f"Processing file: {filename}")
        print(f"Full path: {filepath}")
        print("=" * 50)
        
        try:
            if filepath.lower().endswith('.csv'):
                df = pd.read_csv(filepath)
            elif filepath.lower().endswith(('.xlsx', '.xls')):
                df = pd.read_excel(filepath)
            elif filepath.lower().endswith('.json'):
                df = pd.read_json(filepath)
            else:
                # Try to read as CSV by default
                df = pd.read_csv(filepath)
                print(f"Warning: Unknown file type, trying to read as CSV: {filename}")
            
            # Check if required columns exist
            required_columns = ['x', 'y', 'vx', 'vy', 'vz', 'f']
            missing_columns = [col for col in required_columns if col not in df.columns]
            
            if missing_columns:
                print(f"Warning: Missing columns in {filename}: {missing_columns}")
                continue
                
            print(f"DataFrame shape: {df.shape}, columns: {list(df.columns)}")
            dfs.append(df)
            filenames.append(filename)
            
        except Exception as e:
            print(f"Error reading file {filename}: {e}")
            continue
    
    print(f"Successfully processed {len(dfs)} out of {len(file_paths)} files")
    
    # Destroy the root window
    root.destroy()
    
    return dfs, filenames
